package com.jxzn.locust.controller.front;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jxzn.locust.dto.ResultDTO;
import com.jxzn.locust.model.Player;
import com.jxzn.locust.service.PlayerService;
import com.jxzn.locust.support.validator.NormalGroup;

@Controller
@RequestMapping("/front/player")
public class FrontPlayerController {

    @Autowired
    PlayerService playerService;

    /**
     * 程序员报名
     * 
     * @param Player
     * @return
     */
    @SuppressWarnings("unchecked")
    @PostMapping("save")
    @ResponseBody
    public ResultDTO<Player> saveProgramer(Player player) {
        player.setDeleted(Boolean.FALSE);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Player>> set = validator.validate(player, NormalGroup.class);
        if (CollectionUtils.isNotEmpty(set)) {
            return ResultDTO.validator(set);
        }
        Player target = playerService.findByMobile(player.getMobile());
        if (null != target) {
            return ResultDTO.businessError("该手机号已经注册");
        }
        playerService.save(player);

        return ResultDTO.success(player);
    }

    /**
     * 查询详情
     * 
     * @param mobile
     * @return
     */
    @PostMapping("detail")
    @ResponseBody
    public ResultDTO<Player> detail(@RequestParam("mobile") String mobile) {
        Player target = playerService.findByMobile(mobile);
        if (null != target) {
            target.show();
        }
        return ResultDTO.success(target);
    }

}
